package com.shux.kafka.consumer;

import java.util.concurrent.CountDownLatch;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 描述：
 * 循环执行某个任务的线程
 * <pre>HISTORY
 * ****************************************************************************
 *  ID   DATE           PERSON          REASON
 *  1    2017年9月19日      Simba.Hua         Create
 * ****************************************************************************
 * </pre>
 * @author Simba.Hua
 */
public abstract class RepeatThread extends Thread{
	private volatile boolean stop = false;
	private Integer sleepSecords = 0;
	protected Logger logger = LoggerFactory.getLogger(getClass());
	private final CountDownLatch latch = new CountDownLatch(1);
	public RepeatThread(Integer sleepSecords){
		if(sleepSecords != null)
		this.sleepSecords = sleepSecords;
	}
	@Override
	public void run() {
		while( !stop ) {
			try {
				Thread.sleep(sleepSecords);
				repeatWork();
			} catch (InterruptedException e) {
				logger.error("RepeatThread is interrupted", e);
				Thread.currentThread().interrupt();
			}catch (Throwable t) {
				logger.error("execute error", t);
			}
		}
		latch.countDown();
	}
	protected abstract void repeatWork() throws InterruptedException;

	public void shutdown(){
		this.stop = true;
		interrupt();
		try {
			latch.await();
		} catch (InterruptedException e) {
			logger.error("RepeatThread CountDownLatch await is interrupted", e);
			Thread.currentThread().interrupt();
		}
	}
}
